package com.hgy.fxui.controller;

import com.hgy.fxui.model.Supplier;
import com.hgy.fxui.dao.SupplierDao;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Slf4j
@Controller
public class SupplierManagementController {

    @Setter
    private SupplierDao supplierDao;

    @FXML
    private TextField searchField;
    @FXML
    private TableView<Supplier> supplierTable;
    @FXML
    private TableColumn<Supplier, Integer> idColumn;
    @FXML
    private TableColumn<Supplier, String> nameColumn;
    @FXML
    private TableColumn<Supplier, String> contactPersonColumn;
    @FXML
    private TableColumn<Supplier, String> phoneColumn;
    @FXML
    private TableColumn<Supplier, String> addressColumn;
    @FXML
    private TableColumn<Supplier, LocalDate> createTimeColumn;
    @FXML
    private TableColumn<Supplier, Void> actionColumn;

    @FXML
    private VBox editForm;
    @FXML
    private TextField nameField;
    @FXML
    private TextField contactPersonField;
    @FXML
    private TextField phoneField;
    @FXML
    private TextField addressField;

    private final ObservableList<Supplier> supplierList = FXCollections.observableArrayList();
    private Supplier currentSupplier;
    private boolean isUISetupCompleted = false;

    @FXML
    public void initialize() {
        log.info("FXML初始化开始...");

        if (!isUISetupCompleted) {
            basicUIInitialize();
            isUISetupCompleted = true;
        }

        log.info("FXML初始化完成...");
    }

    public void fullInitialize() {
        log.info("开始完整初始化供应商管理...");

        if (supplierDao == null) {
            throw new IllegalStateException("supplierDao未初始化!");
        }

        if (!isUISetupCompleted) {
            basicUIInitialize();
            isUISetupCompleted = true;
        }

        supplierTable.setSelectionModel(null);

        loadSupplierData();
        log.info("完整初始化完成");
    }

    private void basicUIInitialize() {
        log.debug("执行基础UI初始化...");

        // 初始化表格列
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        contactPersonColumn.setCellValueFactory(new PropertyValueFactory<>("contactPerson"));
        phoneColumn.setCellValueFactory(new PropertyValueFactory<>("phone"));
        addressColumn.setCellValueFactory(new PropertyValueFactory<>("address"));
        createTimeColumn.setCellValueFactory(new PropertyValueFactory<>("createTime"));

        // 设置操作列
        setupActionColumn();

        supplierTable.setItems(supplierList);
        editForm.setVisible(false);

        log.debug("基础UI初始化完成");
    }

    public void loadSupplierData() {
        if (supplierDao == null) {
            log.error("尝试加载数据时supplierDao为null!");
            return;
        }

        try {
            log.info("开始从数据库加载供应商数据...");
            List<Supplier> suppliers = supplierDao.getAllSuppliers();

            if (suppliers == null) {
                log.warn("supplierDao.getAllSuppliers()返回null");
            } else {
                log.info("成功加载 {} 条供应商数据", suppliers.size());
                supplierList.setAll(suppliers);
            }
        } catch (Exception e) {
            log.error("加载供应商数据失败", e);
            showAlert("无法加载供应商数据: " + e.getMessage());
        }
    }

    public void refreshData() {
        log.info("刷新供应商数据...");
        loadSupplierData();
    }

    private void setupActionColumn() {
        actionColumn.setCellFactory(param -> new TableCell<>() {
            private final Button editButton = new Button("编辑");
            private final Button deleteButton = new Button("删除");
            private final HBox pane = new HBox(editButton, deleteButton);

            {
                pane.setSpacing(10);
                editButton.getStyleClass().add("btn-edit");
                deleteButton.getStyleClass().add("btn-delete");

                editButton.setOnAction(event -> {
                    Supplier supplier = getTableView().getItems().get(getIndex());
                    handleEdit(supplier);
                });
                deleteButton.setOnAction(event -> {
                    Supplier supplier = getTableView().getItems().get(getIndex());
                    handleDelete(supplier);
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(pane);
                }
            }
        });
    }

    @FXML
    private void handleSearch() {
        String keyword = searchField.getText().trim().toLowerCase();
        if (keyword.isEmpty()) {
            supplierTable.setItems(supplierList);
            log.info("搜索已清除");
        } else {
            ObservableList<Supplier> filteredList = supplierList.filtered(supplier ->
                    supplier.getName().toLowerCase().contains(keyword) ||
                            supplier.getAddress().toLowerCase().contains(keyword)
            );
            supplierTable.setItems(filteredList);
            log.info("实时搜索: {} - 找到 {} 条结果", keyword, filteredList.size());
        }
    }

    @FXML
    private void handleAdd() {
        log.info("用户点击添加新供应商");
        currentSupplier = null;
        clearFormFields();
        editForm.setVisible(true);
    }

    private void handleEdit(Supplier supplier) {
        log.info("编辑供应商: ID={}, 名称={}", supplier.getId(), supplier.getName());
        currentSupplier = supplier;
        populateFormFields(supplier);
        editForm.setVisible(true);
    }

    private void handleDelete(Supplier supplier) {
        log.info("尝试删除供应商: ID={}, 名称={}", supplier.getId(), supplier.getName());

        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText(null);
        alert.setContentText("确定要删除供应商【" + supplier.getName() + "】吗？");

        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            try {
                int rows = supplierDao.delete(supplier.getId());
                if(rows > 0) {
                    supplierList.remove(supplier);
                    log.info("供应商已删除: {}", supplier.getName());
                } else {
                    log.warn("删除操作影响0行记录");
                }
            } catch (Exception e) {
                log.error("删除供应商失败", e);
                showAlert("删除失败: " + e.getMessage());
            }
        }
    }

    @FXML
    private void handleSave() {
        log.info("用户尝试保存供应商信息");

        if (isInputValid()) {
            Supplier supplier = buildSupplierFromFields();
            boolean isNewSupplier = currentSupplier == null;

            try {
                if (isNewSupplier) {
                    // 新增供应商
                    supplier.setCreateTime(LocalDate.now());
                    int rows = supplierDao.insert(supplier);

                    if(rows > 0) {
                        log.info("新增供应商成功: {}", supplier.getName());
                        refreshData();
                    }
                } else {
                    // 编辑现有供应商
                    supplier.setId(currentSupplier.getId());
                    supplier.setCreateTime(currentSupplier.getCreateTime());
                    int rows = supplierDao.update(supplier);

                    if(rows > 0) {
                        log.info("更新供应商成功: {}", supplier.getName());
                        refreshData();
                    }
                }

                editForm.setVisible(false);
                clearFormFields();
                currentSupplier = null;

            } catch (Exception e) {
                log.error("保存供应商失败", e);
                showAlert("保存失败: " + e.getMessage());
            }
        }
    }

    private Supplier buildSupplierFromFields() {
        return Supplier.builder()
                .name(nameField.getText().trim())
                .contactPerson(contactPersonField.getText().trim())
                .phone(phoneField.getText().trim())
                .address(addressField.getText().trim())
                .build();
    }

    private void showAlert(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    @FXML
    private void handleCancel() {
        log.info("用户取消编辑");
        editForm.setVisible(false);
        clearFormFields();
    }

    private void clearFormFields() {
        nameField.clear();
        contactPersonField.clear();
        phoneField.clear();
        addressField.clear();
    }

    private void populateFormFields(Supplier supplier) {
        nameField.setText(supplier.getName());
        contactPersonField.setText(supplier.getContactPerson());
        phoneField.setText(supplier.getPhone());
        addressField.setText(supplier.getAddress());
    }

    private boolean isInputValid() {
        StringBuilder errorMessage = new StringBuilder();

        validateField(nameField, "供应商名称", null, errorMessage);
        validateField(contactPersonField, "联系人", null, errorMessage);
        validateField(phoneField, "联系电话", this::isValidPhone, errorMessage);
        validateField(addressField, "地址", null, errorMessage);

        if (!errorMessage.isEmpty()) {
            showAlert(errorMessage.toString());
            return false;
        }

        return true;
    }

    private boolean isValidPhone(String phone) {
        return phone.matches("^1[3-9]\\d{9}$"); // 简单的手机号验证
    }

    private void validateField(TextField field, String fieldName,
                               Function<String, Boolean> validator, StringBuilder errorMessage) {
        String text = field.getText() != null ? field.getText().trim() : "";

        if (text.isEmpty()) {
            errorMessage.append(fieldName).append("不能为空！\n");
        } else {
            if (validator != null && !validator.apply(text)) {
                errorMessage.append(fieldName).append("格式不正确！\n");
            }
        }
    }
}